var WorkGrid = function($) {
    var workGrid = function(opts) {
        // 定义参数
        this.params = {
            containerId: "contentDiv", // 容器ID
            columns: [], // 显示的列
            url: "", // 数据来源的URL
            pageIndex: 1, // 当前页
            pageSize: 20, // 每页显示的记录数
            pagination: false, // 是否需要分页
            checkbox: false, // 是否需要复选框
            checkboxProperty: false, // 复选框对应的属性
            checkboxPropertyFunc: null, // 每条记录的复选框是否需要显示
            formId: "", // 提交的FORM ID
            searchBar: null, // searchBar对象，用于提交参数
            loadBeforeListener: null, // load前，调用的事件
            loadAfterListener: null, // load后，调用的事件
            renderBeforeListener: null, // render前，调用的事件
            renderAfterListener: null, // render后，调用的事件
            columnDirective: null, // 绑定在列的指令（事件）
            exportTitle: null, // 导出文件的标题
            exportColumns: null // 导出的内容信息（格式：代码,code~名称,name）
        };

        this.tmpPageTotalSize = 1; // 用于存储总页数的临时变量
        this.sortField = "";
        this.sortOrder = "";
        this.loading = false; // 是否正在加载数据中，用于防止过快重复加载数据
        this.tmpDatas = [];

        // 初始化参数
        if (opts.containerId != null) this.params.containerId = opts.containerId;
        if (opts.columns != null) this.params.columns = opts.columns;
        if (opts.url != null) this.params.url = opts.url;
        if (opts.pageIndex != null) this.params.pageIndex = opts.pageIndex;
        if (opts.pageSize != null) this.params.pageSize = opts.pageSize;
        if (opts.pagination != null) this.params.pagination = opts.pagination;
        if (opts.checkbox != null) this.params.checkbox = opts.checkbox;
        if (opts.checkboxProperty != null) this.params.checkboxProperty = opts.checkboxProperty;
        if (opts.checkboxPropertyFunc != null) this.params.checkboxPropertyFunc = opts.checkboxPropertyFunc;
        if (opts.formId != null) this.params.formId = opts.formId;
        if (opts.loadBeforeListener != null) this.params.loadBeforeListener = opts.loadBeforeListener;
        if (opts.loadAfterListener != null) this.params.loadAfterListener = opts.loadAfterListener;
        if (opts.renderBeforeListener != null) this.params.renderBeforeListener = opts.renderBeforeListener;
        if (opts.renderAfterListener != null) this.params.renderAfterListener = opts.renderAfterListener;
        if (opts.columnDirective != null) this.params.columnDirective = opts.columnDirective;
        if (opts.exportTitle != null) this.params.exportTitle = opts.exportTitle;
        if (opts.exportColumns != null) this.params.exportColumns = opts.exportColumns;
        if (opts.searchBar != null) this.params.searchBar = opts.searchBar;

        // 初始化表格的方法
        this.render = function() {
            if (this.params.renderBeforeListener != null) this.params.renderBeforeListener();

            // 初始化下拉框组件
            /*$(document.body).find("input[class='scombobox']").each(function(i, item) {
                SComboboxHelper.create($(item));
            });*/

            $("#" + this.params.containerId).append(this.initTable());

            if (this.params.renderAfterListener != null) this.params.renderAfterListener();

            this.load();
        }

    }

    workGrid.prototype = {
        // 初始化表格
        initTable: function() {
            var html = '<table class="am-table am-table-bordered am-table-hover dataTable work-table" id="table_' + this.params.containerId + '"><thead><tr>';

            if (this.params.checkbox) {
                html += '<th class="ui_grid_chk_th" width="3%"><input id="all_chk_' + this.params.containerId + '" type="checkbox" onclick="_bs_selectedAll(this,\'chk_' + this.params.containerId + '\')"></th>';
            }

            for (var i = 0; i < this.params.columns.length; i++) {
                var col = this.params.columns[i];
                html += '<th';
                if (col.width != null) html += ' style="width:' + col.width + '" ';
                if (col.sort != null) {
                    html += ' class="sorting" sort="' + col.sort + '" role="sort" title="点击按[' + col.display.replace('<br>', '') + ']排序"';
                }
                html += '>';
                html += col.display + '</th>';
            }
            html += '</tr></thead>';

            html += '<tbody id="tbody_' + this.params.containerId + '" style="font-size:12px;"></tbody>';
            html += '</table>';
            html += '<div id="pagination_' + this.params.containerId + '" class="paginationD"></div>';
            html += '<div id="waitDiv_' + this.params.containerId + '" class="ui_grid_loading"></div>';
            return html;
        },

        /**
         * 查询的方法
         * _pageIndex：页码
         * _params：参数
         */
        load: function(_pageIndex, _params) {
            // 检查是否正在加载数据中，如果正在加载中，则阻断后续的加载请求
            if (this.loading) return;
            this.loading = true;

            this.openWaitDiv();
            this.resetCheckboxStatus();

            var columns = this.params.columns;
            var containerId = this.params.containerId;
            var pagination = this.params.pagination;
            var checkbox = this.params.checkbox;
            var checkboxProperty = this.params.checkboxProperty;
            var _this = this;

            if (_pageIndex != null) this.params.pageIndex = _pageIndex;
            var postDataStr = $("#" + this.params.formId).serialize() + "&pageIndex=" + this.params.pageIndex + "&pageSize=" + this.params.pageSize + "&sortField=" + this.sortField + "&sortOrder=" + this.sortOrder;
            if (_params != null) { postDataStr += "&" + _params; }
            if (this.params.searchBar != null) { postDataStr += "&" + this.params.searchBar.getQueryParams(); }

            var url = this.params.url;
            if (url.indexOf("?") != -1) { url += "&_=" + new Date().getTime(); } else { url += "?_=" + new Date().getTime(); }

            // 查询前
            if (this.params.loadBeforeListener != null) this.params.loadBeforeListener();

            $.ajax({
                url: url,
                cache: false,
                dataType: "json",
                data: postDataStr,
                type: "post",
                beforeSend: function() {},
                error: function() {
                    $.toast({ text: '数据加载异常！请检查是否登录超时。', showHideTransition: 'slide', icon: 'error', position: 'top-center' });
                },
                success: function(data_) {
                    data_.pageIndex = parseInt(data_.pageIndex);
                    data_.pageSize = parseInt(data_.pageSize);
                    data_.total = parseInt(data_.total);

                    // 构建显示的数据
                    var data = data_.datas;
                    _this.tmpDatas = data_.datas;

                    var html = "";
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            html += '<tr';
                            if (_this.params.columnDirective != null) {
                                var directiveStr = _this.params.columnDirective(data[i]);
                                html += " " + directiveStr + " ";
                            }
                            html += '>';

                            if (checkbox) {
                                html += '<td style="text-align:center">';
                                if (_this.params.checkboxPropertyFunc == null || _this.params.checkboxPropertyFunc(data[i])) {
                                    html += '<input type="checkbox" name="chk_' + containerId + '" value="' + getVal(checkboxProperty, data[i]) + '" />';
                                }
                                html += '</td>';
                            }

                            for (var j = 0; j < columns.length; j++) {
                                html += '<td';
                                if (columns[j].directive != null) {
                                    var directiveStr = columns[j].directive(data[i]);
                                    html += " " + directiveStr + " ";
                                }
                                html += '>';

                                if (columns[j].view != null) {
                                    var str = "";
                                    if (typeof(columns[j].view) == 'function') {
                                        str = columns[j].view(data[i]);
                                    } else {
                                        str = convertHtmlProp(columns[j].view, data[i]);
                                    }
                                    html += columns[j].maxlength != null ? shortStr(str, columns[j].maxlength) : str;
                                } else if (columns[j].property != null) {
                                    var str = getVal(columns[j].property, data[i]);
                                    html += columns[j].maxlength != null ? shortStr(str, columns[j].maxlength) : str;
                                }
                                html + '</td>';
                            }
                            html += '</tr>';
                        }
                    } else {
                        var colLength = columns.length + (_this.params.checkbox ? 1 : 0);
                        html += '<tr><td style="text-align:center;" colspan="' + colLength + '">没有数据显示！</td></tr>';
                    }

                    // 构建分页栏
                    var pageTotalSize = Math.ceil(data_.total / data_.pageSize);
                    if (isNaN(pageTotalSize)) return;
                    _this.tmpPageTotalSize = pageTotalSize;

                    var totalPageItems = [];
                    var startIndex = Math.floor((data_.pageIndex - 1) / 5) * 5;
                    for (var i = 1; i <= 5; i++) {
                        var index = startIndex++ + 1;
                        if (index <= pageTotalSize) { totalPageItems.push(index); }
                    }

                    var phtml = '<ul class="pagination" style="margin:0px!important">';
                    phtml += '<li><a title="Go最前页" role="goFirstPage" href="javascript:void(0)">««</a></li>';
                    phtml += '<li><a title="Go上一页" role="goPreviousPage" href="javascript:void(0)">«</a></li>';
                    for (var i = 0; i < totalPageItems.length; i++) {
                        phtml += '<li';
                        if (totalPageItems[i] == data_.pageIndex) phtml += ' class="active"';

                        phtml += '><a href="javascript:void(0)" role="goPageIndex" pageindex="' + totalPageItems[i] + '" title="Go第' + totalPageItems[i] + '页">' + totalPageItems[i] + '</a></li>';
                    }
                    phtml += '<li><a title="Go下一页" role="goNextPage" href="javascript:void(0)">»</a></li>';
                    phtml += '<li><a title="Go最后页" role="goLastPage" href="javascript:void(0)">»»</a></li>';
                    phtml += '<div class="paginationDes">共' + data_.total + '条数据，分' + pageTotalSize + '页显示，';
                    phtml += _this.buildPageSizeSelect() + '</div>';

                    $("#tbody_" + containerId).html(html);
                    $("#pagination_" + containerId).html(phtml);

                    _this.bindEvent($("#" + _this.params.containerId)); // 绑定事件
                    _this.closeWaitDiv();

                    // 查询后
                    if (_this.params.loadAfterListener != null) _this.params.loadAfterListener();
                    _this.loading = false;
                },
                complete: function() {}
            });
        },

        // 构建每页多少条的下拉框代码
        buildPageSizeSelect: function() {
            var pageSize = this.params.pageSize;
            var html = '每页显示<select role="goPageSize" class="paginationPz">';
            html += '<option value="10" ' + ((pageSize == 10 ? 'selected=selected' : '')) + '>10</option>';
            html += '<option value="20" ' + ((pageSize == 20 ? 'selected=selected' : '')) + '>20</option>';
            html += '<option value="30" ' + ((pageSize == 30 ? 'selected=selected' : '')) + '>30</option>';
            html += '<option value="40" ' + ((pageSize == 40 ? 'selected=selected' : '')) + '>40</option>';
            html += '<option value="50" ' + ((pageSize == 50 ? 'selected=selected' : '')) + '>50</option>';
            html += '<option value="100" ' + ((pageSize == 100 ? 'selected=selected' : '')) + '>100</option>';
            html += '</select>条数据。';
            return html;
        },

        bindEvent: function(dom) {
            var _this = this;
            // 最前页事件
            dom.find("a[role='goFirstPage']").click(function() {
                _this.params.pageIndex = 1;
                _this.load();
            });

            //上一页事件
            dom.find("a[role='goPreviousPage']").click(function() {
                var previousPageIndex = _this.params.pageIndex - 1;
                if (previousPageIndex <= 0) previousPageIndex = 1;
                _this.params.pageIndex = previousPageIndex;
                _this.load();
            });

            // 下一页事件
            dom.find("a[role='goNextPage']").click(function() {
                var nextPageIndex = _this.params.pageIndex + 1;
                if (nextPageIndex > _this.tmpPageTotalSize) nextPageIndex = _this.tmpPageTotalSize;
                _this.params.pageIndex = nextPageIndex;
                _this.load();
            });

            // 最后页事件
            dom.find("a[role='goLastPage']").click(function() {
                _this.params.pageIndex = _this.tmpPageTotalSize;
                _this.load();
            });

            // 指定跳转到第几页事件
            dom.find("a[role='goPageIndex']").click(function() {
                _this.params.pageIndex = parseInt(jQuery(this).attr("pageindex"));
                _this.load();
            });

            // 指定每页显示的条数
            dom.find("select[role='goPageSize']").change(function() {
                _this.params.pageSize = parseInt(this.value);
                _this.params.pageIndex = 1;
                _this.load();
            });

            // 排序的事件
            dom.find("th[role='sort']").unbind("click"); // 由于每次刷新表格数据都会重新绑定该事件，导致事件重复，因此需要先移除前面的事件再进行绑定
            dom.find("th[role='sort']").click(function() {
                _this.resetSortClass();
                var sField = jQuery(this).attr("sort");
                jQuery(this).removeClass();
                if (_this.sortField == sField) {
                    if (_this.sortOrder == null || _this.sortOrder == "") {
                        _this.sortOrder = "asc";
                        jQuery(this).addClass("sorting_asc");
                    } else if (_this.sortOrder == "asc") {
                        _this.sortOrder = "desc";
                        jQuery(this).addClass("sorting_desc");
                    } else {
                        _this.sortOrder = "asc";
                        jQuery(this).addClass("sorting_asc");
                    }
                } else {
                    _this.sortOrder = "asc";
                    jQuery(this).addClass("sorting_asc");
                }
                _this.sortField = sField;
                _this.params.pageIndex = 1;
                _this.load();
            });

            //
            dom.find('input[type="checkbox"]').click(function() {
                dom.find('tr').removeClass('grid_chk_checked_bg');
                $('input:checkbox[name="chk_' + _this.params.containerId + '"]:checked').parent().parent().addClass('grid_chk_checked_bg');
            });
        },

        // 打开等待的遮罩层
        openWaitDiv: function() {
            var waitDivObj = $("#waitDiv_" + this.params.containerId);
            var gridLeft = $("#table_" + this.params.containerId).position().left;
            var gridTop = $("#table_" + this.params.containerId).position().top;
            var gridWidth = $("#table_" + this.params.containerId).width();
            var gridHeight = $("#table_" + this.params.containerId).height();

            waitDivObj.css({ position: "absolute", left: gridLeft, top: gridTop, width: gridWidth, height: gridHeight, display: "block" });
        },

        // 关闭等待的遮罩层
        closeWaitDiv: function() {
            $("#waitDiv_" + this.params.containerId).css({ display: "none" });
        },

        // 重置排序的样式
        resetSortClass: function() {
            $("#" + this.params.containerId).find("a[role='sort']").each(function(i) {
                jQuery(this).removeClass();
                jQuery(this).addClass("ui_grid_sort_default");
            });
        },

        resetCheckboxStatus: function() {
            $("#all_chk_" + this.params.containerId).attr("checked", false);
        },

        exportDatas: function(url) {
            if (this.params.exportColumns == null) {
                alert("没有配置导出项！");
                return;
            }
            if (url != null) {
                url += "?exportTitle=" + (this.params.exportTitle != null ? this.params.exportTitle : "");
                url += "&exportColumns=" + encodeURIComponent(this.params.exportColumns);
                url += "&" + $("#" + this.params.formId).serialize();
                if (this.params.searchBar != null) { url += "&" + this.params.searchBar.getQueryParams(); }
                window.open(url);
            }
            //
        },

        findData: function(propertyName, propertyVal) {
            for (var i = 0; i < this.tmpDatas.length; i++) {
                if (getVal(propertyName, this.tmpDatas[i]) == propertyVal) {
                    return this.tmpDatas[i];
                }
            }
            return null;
        },

        findDatas: function(propertyName, propertyVals) {
            var datas = [];
            var propertyValArr = propertyVals.split(',');
            for (var i = 0; i < propertyValArr.length; i++) {
                for (var j = 0; j < this.tmpDatas.length; j++) {
                    if (getVal(propertyName, this.tmpDatas[j]) == propertyValArr[i]) {
                        datas.push(this.tmpDatas[j]);
                        break;
                    }
                }
            }
            return datas;
        },

        getDatas: function() {
            return this.tmpDatas;
        }
    };

    /**
     * 根据属性名从对象中找到对应的值
     * @param propName
     * @param dataObj
     * @returns {*}
     */
    function getVal(propName, dataObj) {
        for (var prop in dataObj) {
            if (prop == propName) {
                return dataObj[prop] || '';
            }
        }
    }

    function convertHtmlProp(html, dataObj) {
        if (html.indexOf("{{") != -1 && html.indexOf("}}") != -1) {
            for (var prop in dataObj) {
                if (html.indexOf("{{" + prop + "}}") != -1) {
                    html = html._bs_replaceAll("{{" + prop + "}}", dataObj[prop]);
                }
            }
        }
        return html;
    }

    function shortStr(str, maxlength) {
        if (str.length <= maxlength) {
            return str;
        } else {
            str = str._bs_replaceAll("<", "")._bs_replaceAll(">", "")._bs_replaceAll("\"", "")._bs_replaceAll("'", "");
            return '<span title="' + filterHtmlTag(str) + '">' + str.substr(0, maxlength) + '...</span>';
        }
    }

    function filterHtmlTag(str) {
        return str.replace(/<.*?>/g, "");
    }

    return workGrid;
}(jQuery);

/////////////////////////////////////////////////////

function _bs_selectedAll(obj, chkName) {
    for (var i = 0; i < document.getElementsByName(chkName).length; i++) { document.getElementsByName(chkName)[i].checked = obj.checked }
};

function _bs_getSelectIds(A) {
    var B = _bs_getCheckBoxValue(document.getElementsByName(A));
    if (B == null) {
        return ""
    } else {
        return B
    }
}

function _bs_checkboxSelected(A) {
    return _bs_boxAction(A, "selected")
}

function _bs_getRadioValue(A) {
    return _bs_boxAction(A, "value")
}

function _bs_getCheckBoxValue(A) {
    return _bs_boxAction(A, "value")
}

function _bs_boxAction(C, A, E) {
    var F = "";
    if (C) {
        if (!C[0]) {
            if (A == "selected") {
                return C.checked
            } else {
                if (A == "value") {
                    if (C.checked) { F = C.value }
                } else {
                    if (A == "toggle") {
                        var D = getEventTarget(E);
                        C.checked = D.checked;
                        if (typeof C.onchange == "function") { C.onchange() }
                    }
                }
            }
        } else {
            for (var B = 0; B < C.length; B++) {
                if (A == "selected") {
                    if (C[B].checked) {
                        return C[B].checked
                    }
                } else {
                    if (A == "value") {
                        if (C[B].checked) {
                            if (C[B].type == "radio") { F = C[B].value } else {
                                if (C[B].type == "checkbox") {
                                    if (F != "") { F = F + "," }
                                    F = F + C[B].value
                                }
                            }
                        }
                    } else {
                        if (A == "toggle") {
                            var D = getEventTarget(E);
                            C[B].checked = D.checked;
                            if (typeof C[B].onchange == "function") { C[B].onchange() }
                        }
                    }
                }
            }
        }
    }
    if (A == "selected") {
        return false
    } else {
        return F
    }
}

function _bs_getInputParams(B, F, C, D) {
    if (null == D) { D = "&" }
    var A = B.elements;
    var E = "";
    if (null == C) { C = true }
    for (i = 0; i < A.length; i++) {
        if ("" != A[i].name) {
            if ("params" == A[i].name) {
                continue
            }
            if ((A[i].value == "") && (C == false)) {
                continue
            }
            if (null != F) {
                if (A[i].name.indexOf(F) == 0 && A[i].name.indexOf(".") > 1) {
                    if ((A[i].type == "radio" || A[i].type == "checkbox") && A[i].checked == false) {
                        continue
                    }
                    if (A[i].value.indexOf("&") != -1) { E += D + A[i].name + "=" + escape(A[i].value) } else { E += D + A[i].name + "=" + A[i].value }
                }
            } else {
                if ((A[i].type == "radio" || A[i].type == "checkbox") && A[i].checked == false) {
                    continue
                }
                if (A[i].value.indexOf("&") != -1) { E += D + A[i].name + "=" + escape(A[i].value) } else { E += D + A[i].name + "=" + A[i].value }
            }
        }
    }
    return E
}

function _bs_addInput(C, D, F, A) {
    if (C[D] != null) { C[D].value = F } else {
        if (null == A) { A = "hidden" }
        var E = null;
        if (document.all) {
            var B = "<input name='" + D + "' value='" + F + "' type='" + A + "'>";
            E = C.document.createElement(B)
        } else {
            E = document.createElement("input");
            E.name = D;
            E.value = F;
            E.type = A
        }
        C.appendChild(E)
    }
}

function _bs_buildSelectedVals(A) {
    var C = "";
    var D = document.getElementById(A);
    for (var B = 0; B < D.length; B++) {
        if (D.options[B].selected) {
            if (C != "") { C += "," }
            C += D.options[B].value
        }
    }
    return C
};

String.prototype._bs_replaceAll = function(AFindText, ARepText) {
    var raRegExp = new RegExp(AFindText, "g");
    return this.replace(raRegExp, ARepText);
}

/////////////////////////////////////////////////////

/**
 * 用户缓存查询数据的类
 */
var workSessionStorage = {
    prefix: location.pathname + "/", // 获取路径
    putDatas: function(formId) {
        var form = document.getElementById(formId);
        for (var i = 0; i < form.elements.length; i++) {
            var ele = form.elements[i];
            if (ele.type != 'button' && ele.type != 'checkbox') {
                window.sessionStorage.setItem(this.prefix + ele.name, ele.value);
            }
        }
    },
    getDatas: function(formId) {
        var form = document.getElementById(formId);
        for (var i = 0; i < form.elements.length; i++) {
            var ele = form.elements[i];

            if (ele.type != 'button' && ele.type != 'checkbox') {
                var val = window.sessionStorage.getItem(this.prefix + ele.name);
                ele.value = val;
            }
        }
    }
};

/**
 * 用户缓存查询数据的类(永久缓存)
 */
var workLocalStorage = {
    prefix: location.pathname + "/", // 获取路径
    putDatas: function(formId) {
        var form = document.getElementById(formId);
        for (var i = 0; i < form.elements.length; i++) {
            var ele = form.elements[i];
            if (ele.type != 'button' && ele.type != 'checkbox') {
                window.localStorage.setItem(this.prefix + ele.name, ele.value);
            }
        }
    },
    getDatas: function(formId) {
        var form = document.getElementById(formId);
        for (var i = 0; i < form.elements.length; i++) {
            var ele = form.elements[i];

            if (ele.type != 'button' && ele.type != 'checkbox') {
                var val = window.localStorage.getItem(this.prefix + ele.name);
                ele.value = val;
            }
        }
    }
};